package com.kcl.dfss;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

import com.kcl.dfss.fragments.LoginDialogFragment;
import com.kcl.dfss.fragments.PersonalFragment;
import com.kcl.dfss.fragments.StaticsFragment;
import com.kcl.dfss.fragments.SurveillanceFragment;
import com.kcl.dfss.http.ServerConnection;
import com.kcl.dfss.utils.AppUtils;
import com.kcl.dfss.utils.ApplicationData;
import com.kcl.dfss.utils.ScreenUtils;

public class MainActivity extends FragmentActivity implements
		View.OnClickListener {

	private ImageView mStaticsView;
	private ImageView mSurveiView;
	private ImageView mPersonalView;

	private final int ID_STATICS = 0;
	private final int ID_SURVEILANCE = 1;
	private final int ID_PERSONAL = 2;

	private boolean isLogin = false;
	
	private PersonalFragment mPersonalFrag = null;
	private SurveillanceFragment mSurveilanceFrag = null;
	private StaticsFragment mStaticsFrag = null;
	private LoginDialogFragment mloginFrag = null;

	private static ApplicationData mAppData = null;
	FragmentManager fManager;
	FragmentTransaction fTransaction;
	
	PowerManager powerManager = null;
	WakeLock wakeLock = null;
	private int currentScreen = 200;
	TimeCount timeCount = new TimeCount(60000, 1000);

	private AudioManager audioManager;
	private int maxVolume,currentVolume;
	
	private String TAG = "MainActivity";
	
	private String app_version,server_version,appurl;
	private SharedPreferences mypreferences = null;
	private SharedPreferences prefer = null;
	private Set<String> appset = null;
	private Handler handler = null;
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		//屏幕常亮
		powerManager = (PowerManager) this.getSystemService(this.POWER_SERVICE);
		wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
//		currentScreen = ScreenUtils.getScreenBrightness(MainActivity.this);
		Log.i(TAG, "当前屏幕亮度："+currentScreen);
//		timeCount.start();
		
		mypreferences = getSharedPreferences("first_install", 0);
		mypreferences.edit().putBoolean("FIRST", false).commit();
		
		prefer = getSharedPreferences("shared_login", 0);
		isLogin = prefer.getBoolean("login", false);
		
		fManager = getSupportFragmentManager();
		
		audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		if(currentVolume*100/maxVolume < 47){
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 7, 0);
		}
		playMusic();
		
		initUI();
		Intent i = getIntent();
		int flag = i.getIntExtra("flag", 0);
		if(flag == 0){
			mStaticsView.performClick();
		}
		
//		if(flag == 0){
//			if(isLogin){
//				AppUtils.showdialog(MainActivity.this);
//			}else{
//				setFragment(flag);
//			}
//		}else{
			setFragment(flag);
//		}
		
		mAppData = new ApplicationData(getApplicationContext());
		
		//打开GPS
		/*if(!AppUtils.getGPSState(MainActivity.this)){
//			AppUtils.toggleGPS(MainActivity.this);
//			Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);
			AppUtils.showGPSDialog(MainActivity.this);
		}*/
		
		startLocationService();
		
		app_version = ApplicationData.app_version;
		appset = new HashSet<String>();
		appset = mypreferences.getStringSet("appset", new HashSet<String>());
		if(AppUtils.isNetworkAvailable(MainActivity.this) && !false){
			getAppVersion();
		}
		
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 1){
					Log.i(TAG, "mlgb:"+appset.toString());
					if(!appset.contains(server_version)){
						Log.i(TAG, "server_version:"+server_version);
						Log.i(TAG, "是否存在:"+appset.contains(server_version));
						showAppUpdateDialog();
					}
				}
			}
		};
		
		Log.d(TAG, "onCreate");
	}
	
	public static ApplicationData getAppData() {
		return mAppData;
	}

	private void startLocationService() {
		Intent intent = new Intent(this, LocationService.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startService(intent);
		Log.d(TAG, "Service on start");
	}

	private void stopLocationService() {
		Intent intent = new Intent(this, LocationService.class);
		stopService(intent);
	}
	
	@SuppressLint("Wakelock")
	public void onResume() {
		
		super.onResume();
		
		Log.i(TAG, "执行MainActivity中onResume方法");
		
		wakeLock.acquire();
		ScreenUtils.setScreenBrightness(currentScreen, MainActivity.this);
		timeCount.start();
		
		
	    
		if (mStaticsFrag != null) {
			
			SharedPreferences preferences = getSharedPreferences("shared_login", 0);
			boolean login_state = preferences.getBoolean("login", false);
			if(mStaticsFrag.isVisible()){
				if(!login_state){ 
			    	AppUtils.showdialog(MainActivity.this); 
			    }
			}
			
			mStaticsFrag.onResume();
		}
		if (mSurveilanceFrag != null) {
			mSurveilanceFrag.onResume();
		}
		if (mPersonalFrag != null) {
			mPersonalFrag.onResume();
		}
		Log.d(TAG, "onResume");
	}

	public void onPause() {
		super.onPause();
		wakeLock.release();
		if (mStaticsFrag != null) {
			mStaticsFrag.onPause();
		}
		if (mSurveilanceFrag != null) {
			mSurveilanceFrag.onPause();
		}
		if (mPersonalFrag != null) {
			mPersonalFrag.onPause();
		}
		Log.d(TAG, "onPause");
		
	}

	@SuppressLint("Wakelock")
	public void onDestroy() {
		super.onDestroy();
//		wakeLock.release();
		stopLocationService();
		Log.d(TAG, "onDestroy");
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		ScreenUtils.setScreenBrightness(currentScreen, MainActivity.this);
		timeCount.start();
		return true;
	}
	
	public void initUI() {
		mStaticsView = (ImageView) findViewById(R.id.statics);
		mSurveiView = (ImageView) findViewById(R.id.surveilance);
		mPersonalView = (ImageView) findViewById(R.id.personal);

		mStaticsView.setOnClickListener(this);
		mSurveiView.setOnClickListener(this);
		mPersonalView.setOnClickListener(this);
		
//		mStaticsView.performClick();
	}

	public void setFragment(int index) {
		fTransaction = fManager.beginTransaction();
		clearChioce();
		hideFragments(fTransaction);
		switch (index) {
		case 0:
			mStaticsView.setImageResource(R.drawable.tongji_after);
			if (mStaticsFrag == null) {
				Log.d(TAG, " setFragment staticsFrag is null");
				mStaticsFrag = new StaticsFragment();
				fTransaction.add(R.id.simple_fragment, mStaticsFrag);
			} else {
				fTransaction.show(mStaticsFrag);
			}
			break;

		case 1:
			mSurveiView.setImageResource(R.drawable.jiankong_after);
			if (mSurveilanceFrag == null) {
				Log.d(TAG, " setFragment mSurvelanceFrag is null");
				mSurveilanceFrag = new SurveillanceFragment();
				fTransaction.add(R.id.simple_fragment, mSurveilanceFrag);
			} else {
				fTransaction.show(mSurveilanceFrag);
			}
			break;

		case 2:
			mPersonalView.setImageResource(R.drawable.pc_after);
			if (mPersonalFrag == null) {
				Log.d(TAG, " setFragment PersonalFrag is null");
				mPersonalFrag = new PersonalFragment();
				fTransaction.add(R.id.simple_fragment, mPersonalFrag);
			} else {
				fTransaction.show(mPersonalFrag);
			}
			break;
		}
		fTransaction.commit();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.statics:
			setFragment(ID_STATICS);
			SharedPreferences preferences = getSharedPreferences("shared_login", 0);
			boolean login_state = preferences.getBoolean("login", false);
			boolean gps_remind = preferences.getBoolean("gps_remind", true);
			if(gps_remind){
				if(!AppUtils.getGPSState(MainActivity.this)){
					AppUtils.showGPSDialog(MainActivity.this);
				}
			}
			if(!login_state){
				AppUtils.showdialog(MainActivity.this);
			}else{
				
			}
			break;
		case R.id.personal:
			setFragment(ID_PERSONAL);
			break;
		case R.id.surveilance:
			setFragment(ID_SURVEILANCE);
			break;
		default:
			break;
		}
	}

	private void hideFragments(FragmentTransaction transaction) {
		if (mPersonalFrag != null) {
			transaction.hide(mPersonalFrag);
		}
		if (mSurveilanceFrag != null) {
			transaction.hide(mSurveilanceFrag);
		}
		if (mStaticsFrag != null) {
			transaction.hide(mStaticsFrag);
		}
	}

	public void clearChioce() {
		mStaticsView.setImageResource(R.drawable.tongji_before);
		mSurveiView.setImageResource(R.drawable.jiankong_before);
		mPersonalView.setImageResource(R.drawable.pc_before);
	}
	
	//获取app版本信息
	public void getAppVersion(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String result = ServerConnection.GetApp("");
				try{
					JSONObject jsonObject = new JSONObject(result);
					String success = jsonObject.getString("success");
					String msg = jsonObject.getString("msg");
					if(success.equals("true")){
						String data = jsonObject.getString("data");
						JSONObject object = new JSONObject(data);
						server_version = object.getString("appversion");
						appurl = object.getString("appurl");
						Message message = new Message();
						message.what = 1;
						handler.sendMessage(message);
					}else{
						server_version = app_version;
						Message message = new Message();
						message.what = 1;
						handler.sendMessage(message);
					}
				}catch(JSONException e){
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	//app更新提示对话框
	public void showAppUpdateDialog(){
		Dialog dialog = new AlertDialog.Builder(MainActivity.this)
        .setTitle("系统提示") 
        .setMessage("APP有新版本，是否更新") 
        .setNeutralButton("不再提醒", 
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	/*Log.i(TAG, "server_version:"+server_version);
                	set.add(server_version);
                	Log.i(TAG, "set字符串:"+set.toString());
                	mypreferences.edit().putStringSet("appset", set).commit();*/
                	updateSet();
                	dialog.dismiss();
                }
            })
        .setPositiveButton("更新", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	Uri uri = Uri.parse("http://"+appurl);
				Intent intentView = new Intent(Intent.ACTION_VIEW,uri);
				startActivity(intentView);
                dialog.dismiss();
            }
        }).create();
    dialog.show(); 
	}
	
	public void updateSet(){
		appset.add(server_version);
		Log.i(TAG, "appset字符串:"+appset.toString());
		mypreferences.edit().putStringSet("appset", appset).commit();
		Log.i(TAG, "appset执行后字符串:"+appset.toString());
	}
	
	@Override
	public void onBackPressed() {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getResources().getString(R.string.quit));
		builder.setPositiveButton(getResources().getString(R.string.yes),
				new OnClickListener() {

					@SuppressLint("NewApi")
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(AppUtils.getGPSState(MainActivity.this)){
							AppUtils.toggleGPS(MainActivity.this);
//							Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, false);
						}
						finishAffinity();
					}

				});
		builder.setNegativeButton(getResources().getString(R.string.no),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}
	
	
	//播放音频文件
	public void playMusic(){
		MediaPlayer player = new MediaPlayer().create(MainActivity.this, R.raw.welcome);
		player.start();
	}
	
	class TimeCount extends CountDownTimer{
		
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			
		}
		
		@Override
		public void onTick(long millisUntilFinished) {
			
		}
		
		@Override
		public void onFinish() {
			ScreenUtils.setScreenBrightness(10, MainActivity.this);
		}
		
	}
	
}
